package com.example.algorithm.sort;

import java.util.Arrays;

/**
 * 颜色分类
 * Leetcode-75
 */
public class SortColors {
    public static void main(String[] args) {
        int[] nums = {1, 2, 0};
        new SortColors().sortColors(nums);
        System.out.println(Arrays.toString(nums));
    }

    public void sortColors(int[] nums) {
        // 0的右边界（开区间）
        int zeroRight = 0;
        // 2的左边界（开区间）
        int twoLeft = nums.length - 1;
        // i从0的左边界到2的右边界移动
        int i = zeroRight;
        while (i <= twoLeft) {
            if (nums[i] == 0) {
                swap(nums, i++, zeroRight++);
            } else if (nums[i] == 1) {
                i++;
            } else if (nums[i] == 2) {
                swap(nums, i, twoLeft--);
            }
        }
    }

    private void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
}